import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
const storageName = 'tbbAdminApp'
Vue.use(Vuex)

// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})

const store = new Vuex.Store({
  modules,
  getters,
  mutations: {
    restoreState: (state, params) => {
      state = Object.assign(state, params)
    }
  },
  plugins: [(store) => {
    store.subscribe((mutation, state) => {
      uni.setStorageSync(storageName, state)
    })
  }]
})
const restoreState = () => {
  const savedstate = uni.getStorageSync(storageName)
  if (savedstate) store.commit('restoreState', savedstate)
}
restoreState()

export default store
